<script setup>
import { ref, defineProps, onMounted, watch } from "vue";
import * as echarts from "echarts";
import ecStat from "echarts-stat";


const props = defineProps({
  targetData: Array,
});



console.log("子组件数据1", props.targetData);
watch(
  () => props.targetData,
  () => {
    // console.log("监控绘图数据", newvalue);
    plot()
  }
);
onMounted(() => {plot()});
let histogramChart = ref("");
function plot() {
  
  
  // console.log("子组件数据2", props.targetData);
  if (props.targetData == undefined || props.targetData.length < 1) {
    console.log("绘图数据为空");
    return;
  }
  // 数据做保留小数位数处理
  // let targetData = props.targetData.map((item)=>item.toFixed(3))
  let targetData = props.targetData
  // console.log("绘图数据",targetData)
  histogramChart.value = echarts.init(document.getElementById("histogram"));
  const bins = ecStat.histogram(targetData);
  var interval;
  let min = Infinity;
  let max = -Infinity;

  let data = echarts.util.map(bins.data, function (item, index) {
    // 左刻度
    let x0 = bins.bins[index].x0;
    // 右刻度
    let x1 = bins.bins[index].x1;
    interval = x1 - x0;
    // 获得数据集中最值
    min = Math.min(min, x0);
    max = Math.max(max, x1);
    // item[0]代表刻度的中间值，item[1]代表出现的次数
    return [x0, x1, item[1]];
  });

  // 自定义渲染效果
  function renderItem(params, api) {
    // 这个根据自己的需求适当调节
    var yValue = api.value(2);
    var start = api.coord([api.value(0), yValue]);
    var size = api.size([api.value(1) - api.value(0), yValue]);
    var style = api.style();

    return {
      // 矩形及配置
      type: "rect",
      shape: {
        x: start[0] + 1,
        y: start[1],
        width: size[0] - 2,
        height: size[1],
      },
      style: style,
    };
  }

  const option = {
    title: {
      text: "输出标签概率分布直方图",
      subtext: "",
      // sublink: 'https://github.com/ecomfe/echarts-stat',
      left: "center",
      top: 10,
    },
    color: ["rgb(25, 183, 207)"],
    grid: {
      top: 80,
      containLabel: true,
    },
    xAxis: [
      {
        type: "value",
        min: min,
        max: max,
        interval: interval,
      },
    ],
    yAxis: [
      {
        type: "value",
      },
    ],
    series: [
      {
        name: "height",
        type: "custom",
        renderItem: renderItem,
        label: {
          show: true,
          position: "insideTop",
        },
        encode: {
          // 表示将data中的data[0]和data[1]映射到x轴
          x: [0, 1],
          // 表示将data中的data[2]映射到y轴
          y: 2,
          // 表示将data中的data[2]映射到tooltip
          tooltip: 2,
          // 表示将data中的data[2]映射到label
          label: 2,
        },
        data: data,
      },
    ],
  };
  histogramChart.value.setOption(option);
}

</script>
<template>
  <div>绘图</div>
  <div id="histogram" style="width: 700px; height: 500px">图</div>
</template>
